//
//  This file is part of iPhoneSMS.
//
//  iPhoneSMS is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  iPhoneSMS is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with iPhoneSMS.  If not, see <http://www.gnu.org/licenses/>.
//
//  Messages.m
//  iPhoneSMS
//
//  Created by Billy Cahill on 1/30/10.
//  Copyright 2010 Billy Cahill. 
//

#import "Messages.h"


@implementation Messages

-(void)dealloc {
	[ary release];
	[super dealloc];
}

-init {
	self = [super init];
	curSort = nil;
	
	ary = [[NSMutableArray alloc] init];
	
	return self;
}

-(BOOL)reload {	
	int rv;
	
	char buf[1024];
	getcwd(buf, 1024);
	
	fprintf(stderr, "cwd: %s\n", buf);
	
	NSLog( [NSString stringWithFormat:@"%s", buf ] );
	
	NSString* smsPath = @"/var/tmp/sms.db";
	NSString* contactPath = @"/var/tmp/contact.db";
	
	MyController *cont = [MyController controller];
	
	NSString *str;
	str = [NSString stringWithFormat:@"scp -P \"%@\" \"%@\"@\"%@\":\"%@\" \"%@\"",
		   [cont getIphonePort], [cont getUsername], [cont getIphoneIp], [cont getSmsdb], smsPath];
	rv = system( [str cStringUsingEncoding: 1] );
	
	if ( rv != 0 ) {
		NSLog( @"scp failed for sms.db" );
		return YES;
	}
	
	str = [NSString stringWithFormat:@"scp -P \"%@\" \"%@\"@\"%@\":\"%@\" \"%@\"",
		   [cont getIphonePort], [cont getUsername], [cont getIphoneIp], [cont getContactdb], contactPath];
	
	rv = system( [str cStringUsingEncoding: 1] );
	
	if ( rv != 0 ) {
		NSLog(@"scp failed for contact.db");
		return YES;
	}
	
	NSString* lastdate = @"0";
	if ( [ary count] ) {
		NSArray* sort = [ary sortedArrayUsingFunction:mysort context:@"date"];
		NSDictionary* dct = [sort objectAtIndex:[ary count]-1];
		lastdate = [dct objectForKey:@"date"];
	}
	
	SQLite *lite = [[[SQLite alloc] init] autorelease];
	NSString* sql = [NSString stringWithFormat: @"select substr(m.address, length(m.address)-9,9) as no, m.date as date, m.text as text, m.read as read, sender from( select replace(replace(replace(replace(replace(address,'(',''),')',''),' ',''),'-',''),'+','') as address, date, text, read, case (flags %% 2) when 1 then 'me' else 'them' end as sender from message ) as m where date > %@;",
					 lastdate];
	NSArray* res = [lite database:smsPath executeSQL:sql];
	NSLog(@"%@", sql);
	if ( ![res count] ) {
		return NO;
	}
			
	NSMutableDictionary* conts = [[NSMutableDictionary alloc] init];
	
	sql = [NSString stringWithFormat:@"select p.last as last, p.first as first, c.no as no, p.organization as organization from ( select uid, property, substr( no, length(no)-9, 9 ) as no, record_id from ( select record_id, uid, property, replace(replace(replace(replace(replace(value,'(',''), ')',''),' ',''),'-',''),'+','')  as no  from abmultivalue where property=3 ) as c ) as c join abperson p on p.rowid = c.record_id where length(c.no)>=9  ;"];
	NSArray* tmp = [lite database:contactPath executeSQL:sql];
	NSEnumerator *emu = [tmp objectEnumerator];
	NSDictionary* d;
	while( d = [emu nextObject] ) {
		[conts setObject:d forKey:[d objectForKey:@"no"]];
	}
	
	emu = [res objectEnumerator];
	NSMutableDictionary *msg;
	while( msg = [emu nextObject] ) {
		NSString *stmp = [msg objectForKey:@"date"];
		NSTimeInterval ival = [stmp doubleValue];
		NSDate *dato = [NSDate dateWithTimeIntervalSince1970:ival];
		[msg setObject:dato forKey:@"date"];

		NSString* no = [msg objectForKey:@"no"];
		
		NSDictionary* add = [conts objectForKey:no];
		if ( add ) {
			[msg addEntriesFromDictionary:add];
		} else {
			NSLog(@"no contact found");
			NSLog(no);
		}
		
		NSString* sndr = [msg objectForKey:@"sender"];
		NSString* f, *l, *o;
		f = [msg objectForKey:@"first"];
		l = [msg objectForKey:@"last"];
		o = [msg objectForKey:@"organization"];
		
		NSString* with;
		
		with = [[NSString stringWithFormat:@"%@ %@ %@", f, l, o] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
		if ( [with length] == 0 ) {
			with = @"?";
		}
		
		[msg setObject:with forKey:@"with"];
		
		if ( [sndr isEqual:@"them"] ) {
			sndr = with;
		} else {
			no = @"";
		}
		
		NSString *sendertime = [NSString stringWithFormat:@"%@\n%@\n%@",
								sndr,
								no,
								dato];
		[msg setObject:sendertime forKey:@"sender time"];
	}
	
	NSMutableArray* ret = reverse_ary(ary);
	
	[ret addObjectsFromArray:res];
	
	[ary release];
	ary = reverse_ary(ret);
	[ary retain];
	
	return YES;
}

-(int)count {
	return [ary count];
}

-(NSDictionary*)objectAtIndex:(int)ri {
	return [ary objectAtIndex:ri];
}

-(NSMutableArray*)array {
	return ary;
}

-(NSString*)sort {
	return curSort;
}

-(void)setSort:(NSString*)s {
	curSort = s;
}

@end